<?php

class BF3Player {
	
	private $_name;
	private $_kills;
	private $_score;
	private $_rankImg;
	
	public function __construct($data) {
		$this->hydrate($data);
	}

	public function hydrate($data) {
		foreach($data['list'] as $detail) {
			$stats=$detail['stats'];
			$this->setName($detail['name']);
			$this->setRankImg($stats['rank']['img_medium']);
			$this->setKills($stats['global']['kills']);
			$this->setScore($stats['scores']['score']);
		}
	}
	
	public function name() {
		return $this->_name;
	}
	
	public function kills() {
		return $this->_kills;
	}
	
	public function score() {
		return $this->_score;
	}
	
	public function rankImg() {
		return $this->_rankImg;
	}
	
	public function setName($name) {
		if (is_string($name)) {
			$this->_name = $name;
		}
	}
	
	public function setKills($kills) {
		if (is_int($kills)) {
			$this->_kills = $kills;
		}
	}
	
	public function setScore($score) {
		if (is_int($score)) {
			$this->_score = $score;
		}
	}
	
	public function setRankImg($rankmediumimg) {
		$strrank = explode("/ss", $rankmediumimg);
		$strrank = $strrank[1];
		$crank = 'http://battlelog-cdn.battlefield.com/public/profile/bf3/stats/ranks/medium/ss'.$strrank;
		if (is_string($crank)) {
			$this->_rankImg = $crank;
		}
	}
	
}

class BF3Stats {

	public function getPlayer($requestedPlayer) {
			
		$data=array('players'=>array(),'opt'=>array());

		// List of players
		$data['players'][]=$requestedPlayer;

		// List of options
		$data['opt']['all']=true;

		// Platform can be pc, 360, ps3
		$platform='pc';

		// Convert lists to JSON
		$postdata=array();
		$postdata['players']=json_encode($data['players']);
		$postdata['opt']=json_encode($data['opt']);

		// Run POST Request via CURL
		$c=curl_init('http://api.bf3stats.com/'.$platform.'/playerlist/');
		curl_setopt($c,CURLOPT_HEADER,false);
		curl_setopt($c,CURLOPT_POST,true);
		curl_setopt($c,CURLOPT_USERAGENT,'BF3StatsAPI/0.1');
		curl_setopt($c,CURLOPT_HTTPHEADER,array('Expect:'));
		curl_setopt($c,CURLOPT_RETURNTRANSFER,true);
		curl_setopt($c,CURLOPT_POSTFIELDS,$postdata);
		$data=curl_exec($c);
		$statuscode=curl_getinfo($c,CURLINFO_HTTP_CODE);
		curl_close($c);

		if($statuscode==200) {
			$data=json_decode($data,true);
			return new BF3Player($data);
		}
		else {
			echo "BF3 Stats API error status: ".$statuscode;
		}
		
	}
	
	public static function getList(Array $players) {
		
		$tPlayers = array();
		
		foreach($players as $player) {
			$data = self::getPlayer($player);
			$tPlayers[] = $data;
		}
		return $tPlayers;
		
	}

}
?>